<template>
  <!-- 配件报溢 -->
  <div>
    <!-- 搜索框 -->
    <FormPanel ref="form" :list="form" :cols="4" :labelWidth="'85'" :isSubmitBtn="false" :collapse="false" @formChange="changeHandle" />

    <FilterTable
      ref="table"
      columnsRef="partPartInventoryPartOverflowIndex"
      :isSelectColumn="false"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="tableDataChange"
      :dataSource="resetTableData"
    >
      <template slot="controls">
        <!-- <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="add"
          :disabled="addBtn"
        >添加</el-button>-->
        <!-- <el-button size="small">导出</el-button> -->
        <div>
          <el-button size="small" type="primary" :disabled="buildBtn" @click="newBuild">新建</el-button>
          <el-button size="small" type="primary" :disabled="saveBtn" :loading="savebtnLoading" @click="save">保存</el-button>
          <el-button size="small" type="primary" :disabled="accountBtn" :loading="entryBtnLoading" @click="account">入账</el-button>
          <el-button size="small" type="primary" :disabled="cancelBtn" @click="cancel">取消</el-button>
          <el-button size="small" type="primary" icon="el-icon-printer" :disabled="printBtn" @click="printClick">打印</el-button>
          <el-button size="small" type="primary" :disabled="voidBtn" :loading="cancellation" @click="handleCancellation">作废</el-button>
        </div>
      </template>
    </FilterTable>

    <!-- 报溢单--选择 -->
    <BaseDialog :visible.sync="visibleOverflowListSelection" title="报溢单选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <overflowListSelection :ptype="ptype" @close="visibleOverflowListSelection = false" @getProfitId="getProfitId" />
    </BaseDialog>
    <!-- 盘点单选择 -->
    <BaseDialog :visible.sync="visibleInventoryListSelection" title="盘点单选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <inventoryListSelection :ptype="ptype" @close="visibleInventoryListSelection = false" @getInventoryId="getInventoryId" />
    </BaseDialog>
    <!-- 配件报溢新增 -->
    <BaseDialog :visible.sync="visiblePartOverflowAdd" title="配件报溢新增" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partOverflowAdd @close="visiblePartOverflowAdd = false" />
    </BaseDialog>
    <!-- 配件报溢编辑 -->
    <BaseDialog :visible.sync="visiblePartOverflowEdit" title="配件报溢编辑" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partOverflowEdit :editData="editData" @close="visiblePartOverflowEdit = false" @resetTableData="resetTableDataFn" />
    </BaseDialog>

    <!-- 打印 -->
    <div v-if="showPrint">
      <BasePrint ref="print" :data="printList" template="templatePartOverFlow" />
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getEmployeeNo, getUser } from '@/assets/js/auth';
import { getProfitItem, getProfitItemByInventoryId, searchOverflowList, setProfit, enterInAccount, cancellation } from '@/api/part/partInventory/partOverflow';
import { notifyAction } from '@/utils';

import moment from 'moment';
import OverflowListSelection from './overflowListSelection';
import InventoryListSelection from './inventoryListSelection';
import PartOverflowAdd from './partOverflowAdd';
import PartOverflowEdit from './partOverflowEdit';
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import { dealerPrintApi } from '@/api/repair/index.js';

export default {
  name: 'Overflow',
  components: {
    OverflowListSelection,
    InventoryListSelection,
    PartOverflowAdd,
    PartOverflowEdit
  },
  mixins: [dictionary],
  data() {
    return {
      form: this.createForm(),
      columns: this.createTableColumns(),
      // fetchApi: getProfitItem,
      fetchParams: { xhrAbort: true },
      visibleOverflowListSelection: false,
      visibleInventoryListSelection: false,
      visiblePartOverflowAdd: false,
      visiblePartOverflowEdit: false,
      addBtn: true,
      buildBtn: false,
      saveBtn: true,
      voidBtn: true,
      savebtnLoading: false, // 保存按钮加载状态
      entryBtn: true,
      entryBtnLoading: false, // 入账按钮加载状态
      cancelBtn: true,
      printBtn: true,
      quitBtn: true,
      editBtn: true,
      cancellation: false, // 作废按钮加载状态
      accountBtn: true,
      handleType: '',
      tableData: [], // table数据
      selectedInventoryData: {}, // 选中的盘点单号数据
      selectedProfitData: {}, // 选中的报溢单号数据
      resetTableData: [], // table数据(重置用)
      editData: {}, // 编辑的数据,
      salerList: {}, // 人员列表
      printList: {},
      handlerList: [],
      showPrint: false,
      printParams: {} // 打印参数
    };
  },
  computed: {
    fetchApi() {
      return this.addBtn ? getProfitItem : getProfitItemByInventoryId;
    },
    ptype() {
      return this.$route.meta.ptype;
    }
  },
  created() {
    this.$nextTick(() => {
      this.getSalerList();
      // this.queryPrintParams();
    });
  },
  methods: {
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button disabled={this.editBtn} size="mini" type="text" onClick={() => this.editHandle(props)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库位代码',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '计量单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '是否3C免办',
        //   dataIndex: 'IS_CCC_PART',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '报溢数量',
          dataIndex: 'PROFIT_QUANTITY',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'input'
        },
        {
          title: '报溢单价',
          dataIndex: 'PROFIT_PRICE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'input'
        },
        {
          title: '盘盈金额',
          dataIndex: 'PROFIT_AMOUNT',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'input'
        }
      ];
    },
    createForm() {
      return [
        {
          type: 'INPUT',
          label: '报溢单号',
          fieldName: 'profitNo',
          disabled: false,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.openOverflowSelect}></el-button>;
          },
          onEnter: val => {
            // this.WorkSearch_rono = val;
            this.openOverflowSelect();
          }
        },
        {
          type: 'INPUT',
          label: '盘点单号',
          fieldName: 'inventoryNo',
          disabled: true,
          readonly: true,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.inventoryNoHandle}></el-button>;
          },
          onEnter: val => {
            // this.WorkSearch_rono = val;
            this.inventoryNoHandle();
          }
        },
        {
          type: 'INPUT',
          label: '报溢日期',
          fieldName: 'overflowDate',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经手人',
          fieldName: 'handlePerson',
          disabled: true
          // itemList: []
        }
      ];
    },
    // table数据发生改变
    tableDataChange(e) {
      console.log(e, 'table数据发生改变');
      this.tableData = e;
    },
    // 获得盘点单号
    getInventoryId(val) {
      console.log(val, 'valllllll');
      this.form.find(x => x.fieldName === 'inventoryNo').initialValue = val.INVENTORY_NO;
      this.form.find(x => x.fieldName === 'overflowDate').initialValue = moment(val.INVENTORY_DATE).format('YYYY-MM-DD');
      this.form.find(x => x.fieldName === 'handlePerson').initialValue = this.getHandlerName(val.HANDLER);
      this.selectedInventoryData = val;
      this.fetchParams.xhrAbort = true;
      this.fetchParams = { inventoryNo: val.INVENTORY_NO, xhrAbort: false };
      this.form.find(x => x.fieldName === 'inventoryNo').disabled = true;
      this.addBtn = false;
    },
    // 选择报溢单号点击确定  只有【入账、取消、作废】按钮高亮；【报溢单选择、编辑、新建、保存、打印】置灰
    getProfitId(val) {
      // console.log(val,'res.data val')
      this.accountBtn = false;
      this.form.find(x => x.fieldName === 'profitNo').initialValue = val.profitNo;
      this.form.find(x => x.fieldName === 'inventoryNo').initialValue = val.inventoryNo;
      this.form.find(x => x.fieldName === 'overflowDate').initialValue = moment(val.orderDate).format('YYYY-MM-DD');
      this.form.find(x => x.fieldName === 'handlePerson').initialValue = this.getHandlerName(val.handler);
      console.log(val, 'val:::');
      this.selectedProfitData = val;
      this.fetchParams.xhrAbort = true;
      this.fetchParams = { profitNo: val.profitNo, xhrAbort: false };
      this.$nextTick(() => {
        this.cancelBtn = false;
        this.buildBtn = true;
        this.voidBtn = false;
        this.form.find(x => x.fieldName === 'profitNo').disabled = true;
        this.addBtn = true;
      });
    },

    // 获取经手人
    getHandlerName(val) {
      let employeeName = '';
      console.log(+val, 'valxxxx');
      this.handlerList.forEach(x => {
        // console.log(x, 'xxxxx');
        if (x.userId === +val) {
          console.log(11111111111);
          employeeName = x.employeeName;
        }
      });
      return employeeName;
    },

    changeHandle() {},
    // 点击新建按钮
    newBuild() {
      this.$refs.form.RESET_FORM();
      this.form.find(x => x.fieldName === 'profitNo').disabled = true;
      this.form.find(x => x.fieldName === 'inventoryNo').disabled = false;
      this.form.find(x => x.fieldName === 'overflowDate').initialValue = moment().format('YYYY-MM-DD');
      this.form.find(x => x.fieldName === 'handlePerson').initialValue = getUser();
      this.cancelBtn = false;
      this.buildBtn = true;
      this.saveBtn = false;
    },
    // 行数据点击编辑
    editHandle(e) {
      // console.log(e, '行数据');
      this.editData = e;
      this.visiblePartOverflowEdit = true;
    },
    // 点击保存
    async save() {
      if (this.savebtnLoading) {
        return;
      }
      if (!this.tableData || this.tableData.length <= 0) {
        notifyAction('无法保存空盘盈单', 'warning');
        return;
      }
      this.savebtnLoading = true;
      let formData = await this.$refs.form.GET_FORM_DATA();
      try {
        let res = await setProfit({
          partProfitItemList: this.tableData,
          partProfitId: this.tableData[0].PART_PROFIT_ID,
          handler: formData[1].handlePerson,
          inventoryNo: formData[1].inventoryNo,
          orderDate: formData[1].overflowDate,
          ptype: this.ptype ? this.ptype : null
        });
        this.savebtnLoading = false;
        notifyAction('保存成功');
        // this.cancel();
        this.resetTableData = [];
        this.form[1].disabled = true;
        this.addBtn = true;
        this.buildBtn = false;
        this.saveBtn = true;
        (this.accountBtn = false),
          // 保存成功报溢单号自动填入查询
          // this.getProfitId({ profitNo: res.data.profitNo });
          console.log(res, 'ressss');
        this.getProfitId(res.data);
      } catch (err) {
        this.savebtnLoading = false;
        console.log(err);
      }
    },
    // 点击入账  只有【新建、取消、打印】按钮高亮；【报溢单选择、编辑、保存、入账、作废】置灰
    async account() {
      this.entryBtnLoading = true;
      let formData = await this.$refs.form.GET_FORM_DATA();
      let inNo = formData[1].inventoryNo;
      if (inNo == null || inNo == '' || inNo == undefined) {
        inNo = this.selectedProfitData.inventoryNo;
      }
      try {
        let res = await enterInAccount({
          partProfitId: this.tableData[0].PART_PROFIT_ID,
          profitNo: formData[1].profitNo,
          inventoryNo: inNo,
          partProfitItemList: this.tableData
        });
        this.entryBtnLoading = false;
        if (res.resultCode == 200) {
          notifyAction('入账成功');
          this.cancelBtn = false;
          this.printBtn = false;
          this.addBtn = false;
          this.voidBtn = true;
          this.buildBtn = false;
          this.saveBtn = true;
          this.accountBtn = true;
        }
        // this.cancel();
      } catch (err) {
        console.log(err);
        this.entryBtnLoading = false;
      }
    },
    add() {
      this.visiblePartOverflowAdd = true;
    },
    // 点击取消
    cancel() {
      this.resetTableData = [];
      this.$refs.form.RESET_FORM();
      this.form.find(x => x.fieldName === 'profitNo').disabled = false;
      this.form.find(x => x.fieldName === 'inventoryNo').disabled = true;
      this.cancelBtn = true;
      this.buildBtn = false;
      this.saveBtn = true;
      this.accountBtn = true;
      this.voidBtn = true;
      this.printBtn = true;
    },
    // 点击作废
    async handleCancellation() {
      let formData = await this.$refs.form.GET_FORM_DATA();
      if (this.cancellation) return;
      this.cancellation = true;
      try {
        let res = await cancellation(this.tableData[0].PART_PROFIT_ID);
        this.cancellation = false;

        notifyAction('作废成功');
        this.cancel();
      } catch (err) {
        console.log(err, '作废失败');
        this.cancellation = false;
      }
    },
    // 重新查询table数据
    resetTableDataFn() {
      this.fetchParams.xhrAbort = true;
      this.fetchParams.xhrAbort = false;
    },
    // 打开 报溢单--选择
    openOverflowSelect() {
      this.visibleOverflowListSelection = true;
    },
    // 显示  盘点单选择
    inventoryNoHandle() {
      this.visibleInventoryListSelection = true;
    },
    async getSalerList() {
      // this.$refs.table.START_LOADING();
      let emps = await getDealerUser();
      let obj = {};
      emps.data.map(item => {
        obj[item.userId] = item.employeeName;
      });
      this.salerList = obj;
      this.handlerList = emps.data;
      console.log(emps, 'emps----');
      // this.fetchParams.xhrAbort = false;
      // this.$nextTick(() => {
      //   this.fetchParams.xhrAbort = true;
      // });
      // console.log(this.salerList, '销售列表');
    },

    async printClick() {
      this.showPrint = true;
      let profitNo = this.form.find(x => x.fieldName === 'profitNo').initialValue;
      let res = await getProfitItem({ profitNo });
      console.log(res, 'ress----');
      this.printList = res;
      this.printList.profitNo = profitNo;
      let userId = await getUser();
      this.printList.USER_NAME = this.getHandlerName(userId);
      this.printList.data[0].CREATED_NAME = this.getHandlerName(this.printList.data[0].CREATED_BY);
      this.$refs.print.EXCUTE_PRINT();
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJBY'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style scoped lang="less"></style>
